$include("$theme/popup.css");

$import("lib.douban-api");
$import("lib.douban-api-parser");

$import("qp.controls.CoverFlowView");
$import("qp.controls.EntryDetailView");
    
with ($ns("qp"))
{
    qp.MainPopupClass = function()
    {
        var me = this;
        
        me.keyword = null;
        me.entries = null;
        
        
        var _coverFlowView = null;
        var _detailView = null;
        
        me.init = function()
        {
            DOUBAN.apikey = "0a9e073b8cb8a2091fda15b2a629e61b";
            
            _coverFlowView = new qp.controls.CoverFlowView($("#coverFlowView"));
            _coverFlowView.bind("selectionchanged", _coverFlowView_onselectionchanged)
            _coverFlowView.init();
            
            _detailView = new qp.controls.EntryDetailView($("#detailView"));
            _detailView.init();
            
            
            $("#keyword").change(function(e) {
                if ($("#keyword").val())
                {
                    me.searchEntries($("#keyword").val());
                }
            });
            
            me.keyword = decodeURIComponent(location.search).replace("?keyword=", "");
            me.searchEntries();
        };
        
        
        me.searchEntries = function(p_keyword)
        {
            if (p_keyword != null)
            {
                me.keyword = p_keyword;
            }
            
            $("#keyword").val(me.keyword);
            
            
            mx.indicate("正在查询影片资料库，请稍候...", { type: "search" });
            
            DOUBAN.searchMovies({
                maxresults: 5,
                keyword: me.keyword, 
                callback: function(raw) {
                    result = DOUBAN.parseFeed(raw);
                    _searchEntries_callback(result);
                    mx.$indicator.fadeOut("fast");
                }
            });
        };
        
        
        
        function _searchEntries_callback(p_result)
        {
            console.log("Search Result:");
            console.log(p_result.entries);
            
            if (p_result.entries.length > 0)
            {
                me.entries = p_result.entries;
                _coverFlowView.loadEntries(me.entries);
            }
            else
            {
                mx.indicate("没有查找到符合条件的影片", { duration: 2000 });
            }
        }
        
        function _coverFlowView_onselectionchanged(e)
        {
            _detailView.loadEntry(_coverFlowView.selection);
        }
        
        return me;
    };
    
    qp.MainPopup = new qp.MainPopupClass();
}